//package com.itstyle.seckill.util.statusflow;
//
//import cn.gogpay.dcb.common.dto.ResultCode;
//import cn.gogpay.dcb.common2.result.ResultDTO;
//import cn.gogpay.dcb.common2.util.AmtUtil;
//import cn.gogpay.dcb.mall.common.constant.ApiResultCode;
//import cn.gogpay.dcb.mall.common.dto.CommodityAppDTO;
//import cn.gogpay.dcb.mall.common.dto.edge.form.CancelOrderForm;
//import cn.gogpay.dcb.mall.common.enums.EdgeMethod;
//import cn.gogpay.dcb.mall.common.enums.order.OrderClassificationEnum;
//import cn.gogpay.dcb.mall.common.enums.order.OrderStatusEnum;
//import cn.gogpay.dcb.mall.common.enums.order.OrderTypeEnum;
//import cn.gogpay.dcb.mall.common.feign.dto.merchant.StoreIntroductionVO;
//import cn.gogpay.dcb.mall.common.service.CommodityCommonService;
//import cn.gogpay.dcb.mall.common.service.MallEdgeService;
//import cn.gogpay.dcb.mall.common.service.MerchantCommonService;
//import cn.gogpay.dcb.mall.order.admin.form.NotifyOrderStatusForm;
//import cn.gogpay.dcb.mall.order.admin.form.OrderNoForm;
//import cn.gogpay.dcb.mall.order.annotation.MallOrderMachine;
//import cn.gogpay.dcb.mall.order.annotation.OnOrderStatusEvent;
//import cn.gogpay.dcb.mall.order.common.config.AppConfig;
//import cn.gogpay.dcb.mall.order.common.constant.Constants;
//import cn.gogpay.dcb.mall.order.common.enums.OrderStatusEvent;
//import cn.gogpay.dcb.mall.order.common.enums.ReasonStatus;
//import cn.gogpay.dcb.mall.order.dao.*;
//import cn.gogpay.dcb.mall.order.entity.*;
//import cn.gogpay.dcb.mall.order.feign.OrderMarketingCouponClient;
//import cn.gogpay.dcb.mall.order.feign.TradePayClient;
//import cn.gogpay.dcb.mall.order.feign.dto.tradepay.TradeOrderDTO;
//import cn.gogpay.dcb.mall.order.mq.dto.OrderStatusChangeDTO;
//import cn.gogpay.dcb.mall.order.mq.dto.SkillStatisticsMqDTO;
//import cn.gogpay.dcb.mall.order.web.flow.dto.EventTargetMethod;
//import cn.gogpay.dcb.mall.order.web.flow.dto.MethodParam;
//import cn.gogpay.dcb.mall.order.web.flow.dto.OrderStatusFlux;
//import cn.gogpay.dcb.mall.order.web.flow.form.AbstractFlowForm;
//import cn.gogpay.dcb.mall.order.web.service.MallTransactionalService;
//import cn.gogpay.dcb.sensor.data.common.model.event.SQuXiaoDingDan;
//import cn.gogpay.dcb.sensor.data.sdk.DcbSensorDataClient;
//import cn.gogpay.dcb.springboot.lock.redis.autoconfigure.lock.RedisDistributedLock;
//import cn.gogpay.dcb.trade.common.constants.CommonMqConstants;
//import cn.gogpay.dcb.trade.common.dto.OrderStatusNotifyDTO;
//import cn.gogpay.dcb.trade.common.enums.OrderDiscountType;
//import cn.gogpay.dcb.trade.common.feign.form.OrderCancelDTO;
//import cn.gogpay.dcb.trade.common.form.PreOrderForm;
//import com.alibaba.fastjson.JSON;
//import com.querydsl.jpa.impl.JPAQueryFactory;
//import com.querydsl.jpa.impl.JPAUpdateClause;
//import io.seata.core.context.RootContext;
//import io.swagger.annotations.ApiParam;
//import org.apache.commons.lang3.StringUtils;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.amqp.rabbit.core.RabbitTemplate;
//import org.springframework.aop.support.AopUtils;
//import org.springframework.beans.BeanUtils;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.context.ApplicationContext;
//import org.springframework.context.annotation.Lazy;
//import org.springframework.stereotype.Service;
//import org.springframework.transaction.annotation.Propagation;
//import org.springframework.transaction.annotation.Transactional;
//import sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl;
//
//import javax.annotation.Resource;
//import java.lang.reflect.InvocationTargetException;
//import java.lang.reflect.Method;
//import java.lang.reflect.Parameter;
//import java.math.BigDecimal;
//import java.time.LocalDateTime;
//import java.time.ZoneOffset;
//import java.time.format.DateTimeFormatter;
//import java.util.*;
//import java.util.concurrent.CompletableFuture;
//import java.util.concurrent.Executor;
//import java.util.function.Consumer;
//import java.util.function.Function;
//import java.util.stream.Collectors;
//
///**
// * 订单状态统一流转服务类，所有的订单状态变更请求都由这里发送
// *
// * @author chenglong@gogpay.cn
// * @date 2021年8月9日, 0009
// */
//@Service
//public class OrderStatusFlowService {
//    private Logger logger = LoggerFactory.getLogger(getClass());
//
//    /**
//     * 存储订单事件响应方法体
//     */
//    private final Map<OrderClassificationEnum, Map<OrderStatusEvent, EventTargetMethod>> methods;
//    /**
//     * 存储订单类型对应的状态机Service类
//     */
//    private final Map<OrderClassificationEnum, Object> services;
//    /**
//     * 构造方法，初始化状态机服务实例和事件方法
//     *
//     * @param applicationContext Spring 上下文对象
//     */
//    public OrderStatusFlowService(ApplicationContext applicationContext) {
//
//        this.methods = new HashMap<>();
//        this.services = new HashMap<>();
//        Map<String, Function<OrderStatusFlux<?>, Object>> fluxParamsFuncMap = new HashMap<>();
//
//        fluxParamsFuncMap.put("orderNo", OrderStatusFlux::getOrderNo);
//        fluxParamsFuncMap.put("reasonSlots", OrderStatusFlux::getReasonSlots);
//        fluxParamsFuncMap.put("operationName", OrderStatusFlux::getOperationName);
//
//
//        //获取所有的状态机实例，实例必须由Spring托管
//        Map<String, Object> beansWithAnnotation = applicationContext.getBeansWithAnnotation(MallOrderMachine.class);
//
//        for (Map.Entry<String, Object> entry : beansWithAnnotation.entrySet()) {
//            //获取实例代理的原始类
//            Class<?> targetClass = AopUtils.getTargetClass(entry.getValue());
//
//            //获取状态机描述注解
//            MallOrderMachine mallOrderMachine = targetClass.getAnnotation(MallOrderMachine.class);
//            if (mallOrderMachine != null) {
//                Map<OrderStatusEvent, EventTargetMethod> eventMethodMap = new HashMap<>();
//                methods.put(mallOrderMachine.value(), eventMethodMap);
//                services.put(mallOrderMachine.value(), entry.getValue());
//
//                Method[] methods = targetClass.getMethods();
//                for (Method method : methods) {
//                    //遍历状态机服务实例的所有方法，得到所有的事件方法
//                    OnOrderStatusEvent onOrderStatusEvent = method.getAnnotation(OnOrderStatusEvent.class);
//                    if (onOrderStatusEvent != null) {
//                        if (!method.getReturnType().equals(ResultDTO.class)) {
//                            throw new RuntimeException("订单状态事件方法返回值必须为" + ResultDTO.class.getName() + method);
//                        }
//
//
//                        ParameterizedTypeImpl resultType = (ParameterizedTypeImpl) method.getGenericReturnType();
//                        if (!resultType.getActualTypeArguments()[0].getTypeName().equalsIgnoreCase(Void.class.getTypeName())) {
//                            throw new RuntimeException("订单状态事件方法返回泛型必须为java.lang.Void类型" + method);
//                        }
//
//                        List<MethodParam> params = new ArrayList<>(method.getParameters().length);
//
//                        int index = 0;
//                        for (Parameter parameter : method.getParameters()) {
//                            String name;
//                            Function<OrderStatusFlux<?>, Object> paramFunction = null;
//                            ApiParam apiParam = parameter.getAnnotation(ApiParam.class);
//
//                            if (parameter.getType().equals(OrderStatusFlux.class)) {
//                                paramFunction = (flux -> flux);
//                            }
//                            if (parameter.getType().equals(OrderEntity.class)) {
//                                paramFunction = OrderStatusFlux::getOrderEntity;
//                            }
//                            if (parameter.getType().equals(ReasonStatus.class)) {
//                                paramFunction = OrderStatusFlux::getReason;
//                            }
//                            if (parameter.getType().equals(OrderStatusEvent.class)) {
//                                paramFunction = OrderStatusFlux::getEvent;
//                            }
//                            if (parameter.getType().getSuperclass().equals(AbstractFlowForm.class)) {
//                                paramFunction = OrderStatusFlux::getEventSource;
//                            }
//                            if (paramFunction == null) {
//
//                                if (apiParam != null && StringUtils.isNotBlank(apiParam.name())) {
//                                    name = apiParam.name();
//                                } else {
//                                    name = parameter.getName();
//                                }
//
//                                if (name == null) {
//                                    continue;
//                                }
//                                paramFunction = fluxParamsFuncMap.get(name);
//                            }
//
//                            if (paramFunction != null) {
//                                params.add(new MethodParam(index, paramFunction, apiParam));
//                                index++;
//                            }
//                        }
//
//                        eventMethodMap.put(onOrderStatusEvent.value(), new EventTargetMethod(method, onOrderStatusEvent, params));
//                    }
//                }
//            }
//        }
//    }
//
//
//    /**
//     * 触发订单状态流转事件
//     *
//     * @param form     流转参数
//     * @param consumer 回调函数，会将变更后的最新订单实体回调，仅变更成功才会触发回调
//     * @return 返回订单状态变更结果
//     */
//    @Transactional(propagation = Propagation.NOT_SUPPORTED)
//    public <T extends AbstractFlowForm> ResultDTO<Void> startFlow(OrderStatusFlux<T> form, Consumer<OrderEntity> consumer) {
//        logger.info("开始变更订单状态，form={}", form);
//        String lockKey = Constants.LockKey.UPDATE_ORDER_STATUS_LOCK + form.getOrderNo();
//
//        try {
//            redisDistributedLock.lock(lockKey);
//            OrderEntity order = orderRepository.findById(form.getOrderNo()).orElse(null);
//            if (order == null) {
//                return new ResultDTO<>(ResultCode.serverError().code(), "订单信息不存在");
//            }
//            if (form.getEvent() == OrderStatusEvent.CLOSE) {
//                if (order.getActualReceivable().equals(0)) {
//                    //零元单
//                    if (form.getReason() == ReasonStatus.ADMIN_CLOSE
//                            || form.getReason() == ReasonStatus.AUTO_CLOSE
//                            || form.getReason() == ReasonStatus.USER_CLOSE) {
//                        return ResultDTO.failure("订单正在同步支付信息，无法关闭");
//                    }
//                }
//            }
//            //获取状态机服务类，该对象为Spring的托管Bean
//            Object targetService = this.services.get(order.getOrderClassification());
//            if (targetService == null) {
//                return ResultDTO.failure("订单状态机不存在");
//            }
//
//            //获取事件响应方法
//            EventTargetMethod method = methods.get(order.getOrderClassification()).get(form.getEvent());
//            if (method == null) {
//                return ResultDTO.failure("订单状态方法不存在");
//            }
//            form.setOrderEntity(order);
//
//            logger.info("订单状态变更：order={}，method={}",order,method.getBehindStatus());
//            if (method.getEvent().behindStatus().length > 0) {
//                //判断订单的前置状态是否合法
//                if (!form.isForceUpdate() && !method.getBehindStatus().contains(order.getOrderStatus())) {
//                    return new ResultDTO<>(ApiResultCode.ORDER_STATUS_HAS_CHANGED,
//                            "订单状态已变更，请刷新重试");
//                }
//            }
//
//            if (form.getEvent() == OrderStatusEvent.CLOSE) {
//                if (mallEdgeService.support(order.getUnitOrgCode(), EdgeMethod.CANCEL_ORDER)) {
//                    CancelOrderForm cancelOrderForm = new CancelOrderForm();
//                    cancelOrderForm.setMallOrderNo(order.getOrderNo());
//                    cancelOrderForm.setCancelReason(form.getReason().getReason(form.getReasonSlots()));
//                    ResultDTO<Void> cancelOrderResult = mallEdgeService.cancelOrder(order.getUnitOrgCode(),
//                            cancelOrderForm);
//                    logger.info("调用边界取消订单结果,form={},result={}", cancelOrderForm, cancelOrderResult);
//                    if (!cancelOrderResult.isSuccess() && order.getOrderClassification() != OrderClassificationEnum.TRAVEL) {
//                        return ResultDTO.failure(cancelOrderResult.getMsg());
//                    }
//                }
//            }
//
//            logger.info("开始更新订单状态{}", form);
//
//
//            //构造参数
//            Object[] args = new Object[method.getParams().size()];
//            method.getParams().stream().map(param -> {
//                        return param.getValue(form);
//                    }).collect(Collectors.toList())
//                    .toArray(args);
//
//            //反射调用事件方法
//            Object invoke = method.getMethod().invoke(targetService, args);
//            logger.info("更新订单状态结果:{},{}", form, invoke);
//            final LocalDateTime changeTime = LocalDateTime.now();
//            ResultDTO<Void> updateResult = (ResultDTO<Void>) invoke;
//
//            if (updateResult.isSuccess()) {
//                OrderEntity tempOrder = mallTransactionalService.get(() -> {
//                    JPAUpdateClause updateClause = jpaQueryFactory.update(QOrderEntity.orderEntity)
//                            .set(QOrderEntity.orderEntity.changeStatusTime, changeTime);
//                    if (form.getReason() != null) {
//                        updateClause.set(QOrderEntity.orderEntity.reasonStatus, form.getReason());
//                    }
//
//                    updateClause.where(QOrderEntity.orderEntity.orderNo.eq(order.getOrderNo()))
//                            .execute();
//                    return orderRepository.findById(form.getOrderNo()).orElse(null);
//                });
//
//                try {
//                    mallTransactionalService.newTransaction(() -> {
//                        OrderSnapshotEntity orderSnapshotEntity = new OrderSnapshotEntity();
//                        BeanUtils.copyProperties(tempOrder, orderSnapshotEntity);
//                        orderSnapshotEntity.setCreateTime(changeTime);
//                        orderSnapshotEntity.setUpdateTime(changeTime);
//                        orderSnapshotRepository.saveAndFlush(orderSnapshotEntity);
//                    });
//                } catch (Exception e) {
//                    logger.info("保存订单快照异常", e);
//                }
//
//                CompletableFuture.runAsync(() -> {
//                            RootContext.unbind();
//
//                            OrderConfigEntity orderConfig = orderConfigRepository.findByOrderNo(order.getOrderNo());
//
//                            List<OrderCommodityEntity> commodityEntities = orderCommodityRepository.findAllByOrderNo(order.getOrderNo());
//
//                            if (form.getReason() == ReasonStatus.ADMIN_CLOSE
//                                    || form.getReason() == ReasonStatus.USER_CLOSE
//                                    || form.getReason() == ReasonStatus.AUTO_CLOSE) {
//                                mallTransactionalService.newTransaction(() -> {
//                                    this.returnOrderCoupon(tempOrder.getParentOrderId(), tempOrder.getDataYear(), tempOrder.getDcbUserId(), form.getReason());
//                                });
//                            }
//
//                            if (form.getReason() == ReasonStatus.ADMIN_CLOSE
//                                    || form.getReason() == ReasonStatus.SALE_AFTER_CLOSE
//                                    || form.getReason() == ReasonStatus.USER_CLOSE
//                                    || form.getReason() == ReasonStatus.AUTO_CLOSE) {
//
//                                List<OrderDiscountEntity> orderDiscounts = orderDiscountRepository.findAllByOrderNo(order.getOrderNo());
//                                OrderDiscountEntity couponDiscount = orderDiscounts.stream().filter(item -> {
//                                    return item.getOrderDiscountType() == OrderDiscountType.COUPON;
//                                }).findFirst().orElse(null);
//
//                                OrderDiscountEntity groupDiscount = orderDiscounts.stream().filter(item -> {
//                                    return item.getOrderDiscountType() == OrderDiscountType.GROUP;
//                                }).findFirst().orElse(null);
//
//                                String commodityIdList = commodityEntities.stream().map(OrderCommodityEntity::getRefCommodityId).distinct()
//                                        .collect(Collectors.joining(","));
//                                try {
//                                    dcbSensorDataClient.event()
//                                            .track(
//                                                    SQuXiaoDingDan.quXiaoDingDan
//                                                            .distinctId(order.getUserTel().toString())
//                                                            .orderId(order.getOrderNo())
//                                                            .commodityId(commodityIdList)
//                                                            .cancelReason(form.getReason().getReason(form.getReasonSlots()))
//                                                            .orderActualAmount(AmtUtil.fenToYuan(order.getActualReceivable()))
//                                                            .commodityName(commodityEntities.stream().map(OrderCommodityEntity::getCommodityName).collect(Collectors.joining(",")))
//                                                            .orderActivityType(BigDecimal.valueOf(order.getOrderActivityType().getValue()))
//                                                            .payType(order.getPayType().getName())
//                                                            .isUseDiscount(couponDiscount != null ? "是" : "否")
//                                                            .discountName(couponDiscount != null ? couponDiscount.getActivityName() : "无")
//                                                            .discountAmount(couponDiscount != null ? AmtUtil.fenToYuan(couponDiscount.getAmount()) : BigDecimal.ZERO)
//                                                            .isUseCollage(groupDiscount != null ? "是" : "否")
//                                                            .collageId(groupDiscount != null ? groupDiscount.getRefActivityId() : "无")
//                                                            .collageName(groupDiscount != null ? groupDiscount.getActivityName() : "无")
//                                                            .collageAmount(groupDiscount != null ? AmtUtil.fenToYuan(groupDiscount.getAmount()) : BigDecimal.ZERO)
//
//                                            );
//                                } catch (Exception e) {
//                                    logger.error("处理埋点发送异常", e);
//                                }
//
//                            }
//
//                            this.sendOrderStatusNotify(tempOrder, changeTime, form.getReason());
//
//                            if (tempOrder.getOrderType() == OrderTypeEnum.SECKILL) {
//                                logger.info("秒杀订单通知判断，orderNo={},orderType={},orderStatus:{}", tempOrder.getOrderNo(),
//                                        tempOrder.getOrderType(), tempOrder.getOrderStatus());
//                                if (tempOrder.getOrderStatus() == OrderStatusEnum.WAIT_SHIPPING
//                                        || (tempOrder.getOrderClassification() == OrderClassificationEnum.VIRTUAL && tempOrder.getOrderStatus() == OrderStatusEnum.DONE
//                                        || (tempOrder.getOrderClassification() == OrderClassificationEnum.DISPATCH && tempOrder.getOrderStatus() == OrderStatusEnum.UN_EXCHANGE))
//                                ) {
//                                    OrderCommodityEntity commodityEntity = commodityEntities.get(0);
//                                    SkillStatisticsMqDTO skillStatisticsMqDTO = new SkillStatisticsMqDTO();
//                                    skillStatisticsMqDTO.setSkillActivityId(orderConfig.getRefActivityId());
//                                    skillStatisticsMqDTO.setResourceId(commodityEntity.getRefCommodityId());
//                                    skillStatisticsMqDTO.setResourceName(commodityEntity.getCommodityName());
//                                    skillStatisticsMqDTO.setSkuId(commodityEntity.getRefSkuId());
//                                    skillStatisticsMqDTO.setSkuName(commodityEntity.getCommoditySpecs());
//                                    skillStatisticsMqDTO.setPayAmt(AmtUtil.fenToYuan(order.getActualReceivable()));
//                                    skillStatisticsMqDTO.setSkuNum(commodityEntity.getQuantity());
//                                    skillStatisticsMqDTO.setOrderTime(order.getCreateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
//                                    skillStatisticsMqDTO.setPayTime(tempOrder.getPayTime().format(DateTimeFormatter.ofPattern(
//                                            "yyyy-MM-dd HH:mm:ss")));
//                                    skillStatisticsMqDTO.setUserId(order.getDcbUserId());
//                                    skillStatisticsMqDTO.setUserPhone(order.getUserTel().toString());
//                                    skillStatisticsMqDTO.setOrderNo(tempOrder.getPaySerialNo());
//                                    skillStatisticsMqDTO.setSkillSessionId(orderConfig.getRefSessionId());
//                                    logger.info("发送秒杀订单通知到多卖点,form:{}", skillStatisticsMqDTO);
//                                    rabbitTemplate.convertAndSend("dcbMallActivity-SkillActivityStatisticsQueue",
//                                            JSON.toJSONString(skillStatisticsMqDTO));
//                                }
//                            }
//
//                        }, orderStatusExecutor)
//                        .exceptionally(ex -> {
//                            logger.error("执行订单状态更改后异步任务异常,orderNo={}", order.getOrderNo(), ex);
//                            return null;
//                        });
//                if (consumer != null) {
//                    OrderEntity entity = orderRepository.findById(order.getOrderNo()).orElse(null);
//                    consumer.accept(entity);
//                }
//
//            }
//
//
//            return updateResult;
//        } catch (IllegalAccessException | InvocationTargetException e) {
//            logger.error("更新订单状态异常:{}", form, e);
//            return ResultDTO.failure(e.getMessage());
//        } finally {
//            redisDistributedLock.releaseLock(lockKey);
//        }
//    }
//
//    public void notifyOrder(NotifyOrderStatusForm form) {
//        OrderEntity order = orderRepository.findById(form.getOrderNo()).orElse(null);
//        if (order != null) {
//            List<OrderCommodityEntity> commodityList = orderCommodityRepository.findAllByOrderNo(order.getOrderNo());
//            order.setPaySerialNo(form.getDcbOrderNo());
//            this.syncOrderToOrderCenter(order, LocalDateTime.now(), commodityList);
//        }
//    }
//
//    private OrderStatusNotifyDTO.DiscountInfo toDiscountInfo(OrderDiscountEntity entity) {
//        OrderStatusNotifyDTO.DiscountInfo discountInfo = new OrderStatusNotifyDTO.DiscountInfo();
//        discountInfo.setOrderDiscountType(Optional.ofNullable(entity.getOrderDiscountType()).orElse(OrderDiscountType.UN_KNOW).getValue());
//        discountInfo.setChannelPoint(entity.getChannelPoint());
//        discountInfo.setAmount(entity.getAmount());
//        discountInfo.setActivityName(entity.getActivityName());
//        discountInfo.setRefActivityId(entity.getRefActivityId());
//        discountInfo.setReturnAmount(entity.getReturnAmount());
//        discountInfo.setActivityRange(entity.getActivityRange());
//        discountInfo.setValidDate(entity.getValidDate());
//        discountInfo.setRule(entity.getRule());
//        return discountInfo;
//    }
//
//
//    public void sendOrderStatusNotify(OrderEntity order, LocalDateTime changeTime, ReasonStatus reason) {
//        List<OrderCommodityEntity> commodityEntities = orderCommodityRepository.findAllByOrderNo(order.getOrderNo());
//        OrderConfigEntity orderConfig = orderConfigRepository.findByOrderNo(order.getOrderNo());
//        OrderStatusNotifyDTO orderStatusNotifyDTO = new OrderStatusNotifyDTO();
//        // 查询优惠详情列表
//        QOrderDiscountEntity qOrderDiscountEntity = QOrderDiscountEntity.orderDiscountEntity;
//        List<OrderDiscountEntity> entityList = jpaQueryFactory.selectFrom(qOrderDiscountEntity)
//                .where(qOrderDiscountEntity.orderNo.eq(order.getOrderNo()))
//                .fetch();
//        List<OrderStatusNotifyDTO.DiscountInfo> discountInfoList = entityList.stream()
//                .map(this::toDiscountInfo)
//                .collect(Collectors.toList());
//
//        logger.info("优惠列表：{} ， discountInfoList = {}",entityList,discountInfoList);
//        orderStatusNotifyDTO.setDiscountInfoList(discountInfoList);
//        orderStatusNotifyDTO.setOrderNo(order.getOrderNo());
//        orderStatusNotifyDTO.setParentOrderId(order.getParentOrderId());
//        orderStatusNotifyDTO.setDcbUserId(order.getDcbUserId());
//        orderStatusNotifyDTO.setOrderType(order.getOrderType().getValue());
//        orderStatusNotifyDTO.setChangeTime(changeTime.format(DateTimeFormatter.ofPattern(
//                "yyyy-MM-dd HH:mm:ss")));
//        orderStatusNotifyDTO.setOrderStatus(order.getOrderStatus().getValue());
//        orderStatusNotifyDTO.setParentOrderId(order.getParentOrderId());
//        orderStatusNotifyDTO.setReason(order.getReason());
//        orderStatusNotifyDTO.setOrderStatus(order.getOrderStatus().getValue());
//        orderStatusNotifyDTO.setReasonStatus(reason.getStatus());
//        orderStatusNotifyDTO.setDcbOrderNo(order.getPaySerialNo());
//        orderStatusNotifyDTO.setBusinessChannelId(order.getRefUserGroupId());
//        orderStatusNotifyDTO.setPayAmount(AmtUtil.fenToYuan(order.getActualReceivable()));
//        orderStatusNotifyDTO.setTotalPrice(AmtUtil.fenToYuan(order.getTotalPrice() + order.getPostFee()));
//        orderStatusNotifyDTO.setQuantity(order.getCommodityQuantity());
//        orderStatusNotifyDTO.setUnitOrgCode(order.getUnitOrgCode());
//        orderStatusNotifyDTO.setOrderClassify(order.getOrderClassification().getStatus());
//        Set<String> sellChannelIdSet = commodityEntities.stream().map(commodity -> {
//            if (StringUtils.isBlank(commodity.getRefSellChannelId())) {
//                return order.getRefUserGroupId();
//            }
//            return commodity.getRefSellChannelId();
//        }).collect(Collectors.toSet());
//        orderStatusNotifyDTO.setSellChannelId(new ArrayList<>(sellChannelIdSet));
//        orderStatusNotifyDTO.setCreateTime(order.getCreateTime().format(DateTimeFormatter.ofPattern(
//                "yyyy-MM-dd HH:mm:ss")));
//        if (order.getOrderType() == OrderTypeEnum.SECKILL) {
//            orderStatusNotifyDTO.setActivityId(orderConfig.getRefActivityId());
//            orderStatusNotifyDTO.setActivitySessionId(orderConfig.getRefSessionId());
//        }
//
//        List<PreOrderForm.SkuInfo> skuInfos = commodityEntities.parallelStream().map(commodity -> {
//            PreOrderForm.SkuInfo skuInfo = new PreOrderForm.SkuInfo();
//            skuInfo.setCommodityId(commodity.getRefCommodityId());
//            skuInfo.setSkuId(commodity.getRefSkuId());
//            skuInfo.setCount(commodity.getQuantity());
//            return skuInfo;
//        }).collect(Collectors.toList());
//        orderStatusNotifyDTO.setSkuInfos(skuInfos);
//
//        if (order.getOrderClassification() != OrderClassificationEnum.DISPATCH_PAY) {
//            List<OrderDiscountEntity> orderDiscountList = orderDiscountRepository.findAllByOrderNo(order.getOrderNo());
//            orderDiscountList.stream().filter(item -> {
//                return item.getOrderDiscountType() == OrderDiscountType.COUPON;
//            }).findFirst().ifPresent(item -> {
//                orderStatusNotifyDTO.setCouponId(item.getRefActivityId());
//            });
//            logger.info("发送订单状态变更同步消息{}", orderStatusNotifyDTO.toString());
//            rabbitTemplate.convertAndSend(CommonMqConstants.MALL_ORDER_NOTIFY_EXCHANGE,
//                    CommonMqConstants.ORDER_STATUS_NOTIFY_TOPIC, JSON.toJSONString(orderStatusNotifyDTO));
//        }
//
//
//        this.syncOrderToOrderCenter(order, changeTime, commodityEntities);
//    }
//
//    public void syncOrderToOrderCenter(OrderEntity order, LocalDateTime changeTime, List<OrderCommodityEntity> commodityEntities) {
//
//        StoreIntroductionVO storeIntroduction = merchantCommonService.getStoreIntroduction(order.getRefMerchantId(), null, null);
//
//        OrderStatusChangeDTO orderStatusChangeDTO = new OrderStatusChangeDTO();
//        orderStatusChangeDTO.setOrderNo(order.getPaySerialNo());
//        if (StringUtils.isBlank(orderStatusChangeDTO.getOrderNo())) {
//            OrderNoForm orderNoForm = new OrderNoForm();
//            orderNoForm.setOrderNo(order.getOrderNo());
//            ResultDTO<TradeOrderDTO> queryDcbOrderNoResult = tradePayClient.getDcbOrderNo(orderNoForm);
//            if (queryDcbOrderNoResult.isSuccess()) {
//                orderStatusChangeDTO.setOrderNo(queryDcbOrderNoResult.getData().getOrderNo());
//            }
//        }
//        orderStatusChangeDTO.setChangeTime(changeTime.toInstant(ZoneOffset.of("+8")).toEpochMilli());
//        orderStatusChangeDTO.setStatus(order.getOrderStatus().getValue().toString());
//        if (order.getOrderClassification() == OrderClassificationEnum.MALL) {
//            if (StringUtils.isNotBlank(order.getOriginalOrderNo())) {
//                orderStatusChangeDTO.setStatus("JM" + order.getOrderStatus().getValue());
//            }
//        }
//        orderStatusChangeDTO.setStoreLogo(order.getMerchantPic());
//        orderStatusChangeDTO.setStoreName(order.getMerchantName());
//        if (storeIntroduction != null) {
//            orderStatusChangeDTO.setStoreUrl(storeIntroduction.getStoreUrl());
//        }
//
//        List<OrderStatusChangeDTO.OrderGoodsInfo> goodsList = commodityEntities.stream().map(item -> {
//            OrderStatusChangeDTO.OrderGoodsInfo orderGoodsInfo = new OrderStatusChangeDTO.OrderGoodsInfo();
//            orderGoodsInfo.setId(item.getRefCommodityId());
//            orderGoodsInfo.setName(item.getCommodityName());
//            orderGoodsInfo.setPrice(AmtUtil.fenToYuan(item.getUnitPrice()));
//            orderGoodsInfo.setTotalAmt(AmtUtil.fenToYuan(item.getTotalPrice()));
//            orderGoodsInfo.setStandard(item.getCommoditySpecs());
//            orderGoodsInfo.setIcon(item.getCommodityPic());
//            orderGoodsInfo.setCount(item.getQuantity());
//
//            CommodityAppDTO commodityBaseInfo = commodityCommonService.getCommodityBaseInfo(item.getRefMerchantId());
//            if (commodityBaseInfo != null) {
//                orderGoodsInfo.setUrl(commodityBaseInfo.getPreviewUrl());
//            }
//            return orderGoodsInfo;
//        }).collect(Collectors.toList());
//        orderStatusChangeDTO.setGoodsList(goodsList);
//
//        rabbitTemplate.convertAndSend("trade-center-business-notify-exchange", "order-status-notify", JSON.toJSONString(orderStatusChangeDTO));
//        logger.info("发送订单状态同步信息到交易中心={}", orderStatusChangeDTO);
//    }
//
//    private void returnOrderCoupon(String parentOrderId, int dataYear, String userId, ReasonStatus reasonStatus) {
//        QOrderEntity qOrder = QOrderEntity.orderEntity;
//        List<OrderEntity> orders = jpaQueryFactory.selectFrom(qOrder)
//                .where(qOrder.parentOrderId.eq(parentOrderId))
//                .where(qOrder.dcbUserId.eq(userId))
//                .where(qOrder.dataYear.eq(dataYear))
//                .fetch();
//
//        ParentOrderEntity parentOrder = parentOrderRepository.findByIdAndDataYear(orders.get(0).getParentOrderId(), orders.get(0).getDataYear());
//        if (StringUtils.isNotBlank(parentOrder.getCouponId())) {
//            long closeOrderCount = orders.stream()
//                    .filter(item -> {
//                        return item.getOrderStatus() == OrderStatusEnum.CLOSE;
//                    }).count();
//            if (closeOrderCount == orders.size()) {
//                OrderCancelDTO orderCancelDTO = new OrderCancelDTO();
//                if (reasonStatus == ReasonStatus.USER_CLOSE) {
//                    //用户手动关闭
//                    orderCancelDTO.setCancelType(2);
//                } else {
//                    orderCancelDTO.setCancelType(1);
//                }
//                orderCancelDTO.setOrderNo(parentOrderId);
//                orderCancelDTO.setUserId(userId);
//                ResultDTO<Object> cancelResult = orderMarketingCouponClient.orderCancel(orderCancelDTO);
//                logger.info("调用营销中心取消订单结果:form={},result={}", orderCancelDTO, cancelResult);
//            }
//        }
//    }
//}
